#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mtx;//互斥锁
pthread_cond_t cond;//条件变量

//主线程控制新线程
void *ctrl(void *args)
{
    std::string name = (char*)args;
    while(1)
    {
        std::cout << "master say : begin work" << std::endl;
        pthread_cond_broadcast(&cond);
        sleep(2);
    }
}
void *work(void *args)
{
    int number = *(int*)args;
    delete (int*)args;
    while(1)
    {
        pthread_cond_wait(&cond, &mtx);//等待条件变量
        std::cout << "worker: " << number << " is working ..." << std::endl;
    }
}
#define NUM 3
int main()
{
    pthread_mutex_init(&mtx, nullptr);//初始化这把锁
    pthread_cond_init(&cond, nullptr);//初始化条件变量
    pthread_t master;
    pthread_t worker[NUM];
    pthread_create(&master, nullptr, ctrl, (void*)"boss");
    //创建NUM个线程
    for(int i = 0; i < NUM; i++)
    {
        int *number = new int(i);
        pthread_create(worker+i, nullptr, work, (void*)number);
    }
    //线程等待
    for(int i = 0; i < NUM; i++)
    {
        pthread_join(worker[i], nullptr);
    }

    pthread_join(master, nullptr);//线程等待

    pthread_mutex_destroy(&mtx);//释放锁
    pthread_cond_destroy(&cond);//释放条件变量
    return 0;
}